package com.laxcen.toydemo;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import com.laxcen.intelligenttoy.BLE.DataUtils;
import com.laxcen.intelligenttoy.BLEActivity;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnCheckedChanged;
import butterknife.OnClick;
import pub.devrel.easypermissions.EasyPermissions;

public class MainActivity extends BLEActivity implements EasyPermissions.PermissionCallbacks {
    @BindView(R.id.rv)
    RecyclerView rv;
    @BindView(R.id.bt_operation)
    Button btOperation;
    @BindView(R.id.tv_status_point)
    TextView tvStatusPoint;
    @BindView(R.id.tv_status)
    TextView tvStatus;
    @BindView(R.id.et)
    EditText et;
    @BindView(R.id.ll_et)
    LinearLayout llEt;
    @BindView(R.id.rb_1)
    RadioButton rb1;
    @BindView(R.id.rb_2)
    RadioButton rb2;
    @BindView(R.id.tv_hint)
    TextView tvHint;
    @BindView(R.id.tv_result)
    TextView tvResult;
    @BindView(R.id.ll_btm)
    LinearLayout llBtm;
    @BindView(R.id.ll_second)
    LinearLayout llSecond;
    @BindView(R.id.switch_game)
    Switch switchGame;

    private String[] permissions = new String[]{Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION};
    private int flag = 0;//当前状态 0.断开  1.连接
    private BaseAdapter baseAdapter;
    private List<String> list = new ArrayList<>();
    private int antennaNum = -1;//当前开启天线
    private final static int MSG_READ_TIME = 1000;
    private final static int MSG_WHAT_READ = 0x1;
    private boolean isGame = false;//是否是游戏模式
    private boolean isSecond = false;//切换游戏题目

    @SuppressLint("HandlerLeak")
    Handler readHandler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MSG_WHAT_READ:
                    readTagAllLabel();
                    break;
            }
        }
    };

    @OnClick({R.id.bt_operation, R.id.bt_read, R.id.bt_write, R.id.bt_clear})
    void click(View view) {
        switch (view.getId()) {
            case R.id.bt_operation:
                if (Utils.isDoubleClick()) {
                    return;
                }
                switch (flag) {
                    case 0:
                        //连接
                        connectBLE();
                        break;
                    case 1:
                        //断开
                        disconnectBLE();
                        break;
                }
                break;
            case R.id.bt_read:
                if (Utils.isDoubleClick()) {
                    return;
                }
                showToast("读取中...");
                //读标签
                if (antennaNum == -1) {
                    readTagAllLabel();
                } else {
                    readSingleLabel(antennaNum);
                }
                break;
            case R.id.bt_write:
                if (Utils.isDoubleClick()) {
                    return;
                }
                //写标签
                String hexString = et.getText().toString().trim();
                writeTag(hexString, antennaNum);
                break;
            case R.id.bt_clear:
                //清除
                antennaNum = -1;
                list.clear();
                for (int i = 0; i < 10; i++) {
                    list.add("");
                }
                et.setText("");
                baseAdapter.notifyDataSetChanged();
                break;
        }
    }

    @OnCheckedChanged({R.id.rb_1, R.id.rb_2})
    public void onRadioCheck(CompoundButton view, boolean isChanged) {
        switch (view.getId()) {
            case R.id.rb_1:
                if (isChanged) {
                    isGame = false;
                    changeUI();
                    readHandler.removeMessages(MSG_WHAT_READ);
                    SPU.setTagType(mActivity, 0);
                }
                break;
            case R.id.rb_2:
                if (isChanged) {
                    isGame = true;
                    changeUI();
                    if (flag == 1) {
                        readHandler.removeMessages(MSG_WHAT_READ);
                        readHandler.sendEmptyMessageDelayed(MSG_WHAT_READ, MSG_READ_TIME);
                    }
                    SPU.setTagType(mActivity, 1);
                }
                break;
        }
    }

    @Override
    protected void connectSuccess() {
        btOperation.setText("断开");
        flag = 1;
        tvStatusPoint.setBackgroundResource(R.drawable.green_point);
        tvStatus.setText("状态：已连接");
        Toast.makeText(MainActivity.this, "连接成功", Toast.LENGTH_SHORT).show();
        if (isGame && SPU.getTagType(mActivity) == 1) {
            readHandler.sendEmptyMessageDelayed(MSG_WHAT_READ, MSG_READ_TIME);
        }
    }

    @Override
    protected void disConnect() {
        btOperation.setText("连接");
        flag = 0;
        tvStatusPoint.setBackgroundResource(R.drawable.red_point);
        tvStatus.setText("状态：未连接");
        Toast.makeText(MainActivity.this, "已断开", Toast.LENGTH_SHORT).show();
        antennaNum = -1;
        baseAdapter.notifyDataSetChanged();
        if (isGame) {
            readHandler.removeMessages(MSG_WHAT_READ);
        }
    }

    /**
     * 读取所有标签成功
     *
     * @param data
     */
    @Override
    protected void readAllSuccess(byte[] data) {
//        if (antennaNum != -1) {//有选中天线  单标签
//            list.set(antennaNum, DataUtils.bytes2Str(data).replace("\u0000", ""));
//            baseAdapter.notifyItemChanged(antennaNum);
//            return;
//        }
//        list.clear();
//        int i = 0;
//        while (i < data.length) {
//            if (data[i] == -1) {
//                //空的
//                list.add("");
//                i++;
//            } else {
//                byte[] bytes = new byte[8];
//                System.arraycopy(data, i, bytes, 0, 8);
//                judgeType(bytes);
//                i = i + 8;
//            }
//        }
//        if (isGame && SPU.getTagType(mActivity) == 1) {
//            readHandler.sendEmptyMessageDelayed(MSG_WHAT_READ, MSG_READ_TIME);
//            toCalculate();
//        }
    }

    @Override
    protected void readAllSuccessToList(List<byte[]> dataList) {
        for (int i = 0; i < dataList.size(); i++) {
            byte[] itemBytes = dataList.get(i);
            Log.d("数据项", "size=" + dataList.size() + " index=" + i + " [" + DataUtils.bytes2Str(itemBytes).replace("\u0000", "") + "]");
        }

        if (antennaNum != -1) {//有选中天线  单标签
            if (dataList != null && !dataList.isEmpty()) {
                list.set(antennaNum, DataUtils.bytes2Str(dataList.get(0)).replace("\u0000", ""));
            } else {
                list.set(antennaNum, "");
            }
            baseAdapter.notifyItemChanged(antennaNum);
            return;
        }
        list.clear();
        for (byte[] data : dataList) {
            if (data.length > 0) { //代表有标签
                judgeType(data);
            } else {//无标签
                list.add("");
            }
        }
        if (isGame && SPU.getTagType(mActivity) == 1) {
            readHandler.sendEmptyMessageDelayed(MSG_WHAT_READ, MSG_READ_TIME);
            toCalculate();
        }
    }

    //判断数值的类型
    private void judgeType(byte[] bytes) {
        if (bytes[0] == 0x00) {
            if (bytes[3] == 0x00) {//unicode编码 后4字节
                byte[] dataBytes = new byte[4];
                System.arraycopy(bytes, 4, dataBytes, 0, 4);
                list.add(DataUtils.bytes2Str(dataBytes).replace("\u0000", ""));
            } else if (bytes[3] == 0x01) {//数据位后1字节
                byte[] dataBytes = new byte[1];
                switch (bytes[6]) {
                    case 0x00://汉字的笔划
                    case 0x01://汉语拼音声母韵母
                    case 0x02://通讯辅助设备的所有操作
                    case 0x03://化学元素的编码
                    case 0x04://社交功能模块中的联系人的编码
                    case 0x05://APP所有功能模块的编码
                        System.arraycopy(bytes, 7, dataBytes, 0, 1);
                        break;
                    default:
                        list.add("");
                        break;
                }
                list.add(DataUtils.bytes2Str(dataBytes).replace("\u0000", ""));
            } else if (bytes[3] == 0x02) {//英文单词编码 后4字节
                byte[] dataBytes = new byte[4];
                System.arraycopy(bytes, 4, dataBytes, 0, 4);
                list.add(DataUtils.bytes2Str(dataBytes).replace("\u0000", ""));
            } else if (bytes[3] == 0x03) {//地名编码 后4字节
                byte[] dataBytes = new byte[4];
                System.arraycopy(bytes, 4, dataBytes, 0, 4);
                list.add(DataUtils.bytes2Str(dataBytes).replace("\u0000", ""));
            } else {
                list.add("");
            }
        } else if (bytes[0] == 0x01) {//整数编码 后7字节
            byte[] dataBytes = new byte[7];
            System.arraycopy(bytes, 1, dataBytes, 0, 7);
            list.add(DataUtils.bytes2Str(dataBytes).replace("\u0000", ""));
        } else if (bytes[0] == 0x02) {//浮点数编码 后7字节
            byte[] dataBytes = new byte[7];
            System.arraycopy(bytes, 1, dataBytes, 0, 7);
            list.add(DataUtils.bytes2Str(dataBytes).replace("\u0000", ""));
        } else {
            list.add("");
        }
        baseAdapter.notifyDataSetChanged();
    }

    //计算是否等于苹果的英文单词
    private void toCalculate() {
        StringBuilder sb = new StringBuilder();
        for (String s : list) {
            sb.append(s);
        }
        String resultStr = sb.toString().replace("\u0000", "");
        if (isSecond) {
            if ("read".equalsIgnoreCase("re" + resultStr + "d")) {
                tvResult.setText("答对啦！“阅读”的英文是read");
            } else {
                tvResult.setText("还没有答对哦");
            }
        } else {
            if ("apple".equalsIgnoreCase(resultStr)) {
                tvResult.setText("答对啦！“苹果”的英文是apple");
            } else {
                tvResult.setText("还没有答对哦");
            }
        }
    }

    @SuppressLint("SourceLockedOrientationActivity")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE);//横屏
        setContentView(R.layout.activity_main);
        mActivity = this;
        ButterKnife.bind(this);
        checkPermissions();
        initList();
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        initView();
        changeUI();
    }

    private void initView() {
        if (SPU.getTagType(mActivity) == 0) {
            rb1.setChecked(true);
            isGame = false;
        } else {
            rb2.setChecked(true);
            isGame = true;
        }
        switchGame.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    isSecond = true;
                } else {
                    isSecond = false;
                }
                changeUI();
            }
        });
    }

    private void changeUI() {
        if (isGame) {
            if (isSecond) {
                llSecond.setVisibility(View.VISIBLE);
                tvHint.setText("请将“阅读”的单词拼写完成~");
                tvResult.setText("");
            } else {
                tvHint.setText("请拼出“苹果”的英文单词~");
                tvResult.setText("");
                llSecond.setVisibility(View.GONE);
            }
            llBtm.setVisibility(View.GONE);
            tvHint.setVisibility(View.VISIBLE);
            et.setVisibility(View.GONE);
            llEt.setVisibility(View.GONE);
            tvResult.setVisibility(View.VISIBLE);
            switchGame.setVisibility(View.VISIBLE);
        } else {
            llSecond.setVisibility(View.GONE);
            llBtm.setVisibility(View.VISIBLE);
            et.setVisibility(View.VISIBLE);
            llEt.setVisibility(View.VISIBLE);
            tvHint.setVisibility(View.GONE);
            tvResult.setVisibility(View.GONE);
            switchGame.setVisibility(View.GONE);
        }
    }

    /**
     * 初始化列表
     */
    private void initList() {
        baseAdapter = new BaseAdapter(this, list, R.layout.item) {
            @Override
            protected void setWidget(BaseViewHolder holder, int position) {
                String str = list.get(position);
                holder.setText(R.id.tv, str)
                        .setClickListner(R.id.ll_item, new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                if (!isGame) {
                                    if (flag == 0) {
                                        //当前断开
                                        showToast("请先连接设备！");
                                        return;
                                    }
                                    antennaNum = position;
                                    notifyDataSetChanged();
                                    cutAntenna(antennaNum);
                                }
                            }
                        });
                if (antennaNum == position) {
                    holder.setBackGroundResource(R.id.tv_status_point, R.drawable.green_point);
                } else {
                    holder.setBackGroundResource(R.id.tv_status_point, R.drawable.red_point);
                }
            }
        };
        rv.setAdapter(baseAdapter);
        rv.setLayoutManager(new GridLayoutManager(mActivity, 5));
        for (int i = 0; i < 10; i++) {
            list.add("");
        }
        baseAdapter.notifyDataSetChanged();
    }

    /**
     * 权限检查
     */
    private void checkPermissions() {
        if (!EasyPermissions.hasPermissions(this, permissions)) {//检查是否获取该权限
            //第二个参数是被拒绝后再次申请该权限的解释
            //第三个参数是请求码
            //第四个参数是要申请的权限
            EasyPermissions.requestPermissions(this, getString(R.string.app_name)
                    + "缺少重要权限，拒绝则部分功能将无法运行!", 0, permissions);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {

    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {

    }

    @Override
    protected void onBleScanCallbackScanFinished() {

    }
    @Override
    protected void onBleGattCallbackConnectFail() {

    }
}
